package com.aigou.admin.controller;

import com.aigou.admin.entity.PageEntity;
import com.aigou.admin.entity.ResponseEntity;
import com.aigou.admin.entity.ShopCart;
import com.aigou.admin.service.ShopCartService;
import com.aigou.admin.service.impl.ShopCartServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/shopCarts")
public class ShopCartController extends BaseServlet{

    private ShopCartService shopCartService = new ShopCartServiceImpl();

    // http://localhost:8080/shopCarts?m=findAll
    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws IOException{
        List<ShopCart> shopCarts = shopCartService.getAllShopCarts();
        ResponseEntity.ok(resp,shopCarts);
    }

    // http://localhost:8080/shopCarts?m=findById&id=1432424303
    public void findById(HttpServletRequest req, HttpServletResponse resp) throws IOException{
        String id = req.getParameter("id");
        ShopCart shopCart = shopCartService.getShopCartById(id);
        ResponseEntity.ok(resp,shopCart);
    }

    // http://localhost:8080/shopCarts?m=save&id=1&user_id=1&cart_id=1
    public void save(HttpServletRequest req, HttpServletResponse resp) throws IOException{
        String id = req.getParameter("id");
        String userId = req.getParameter("user_id");
        String cartId = req.getParameter("cart_id");
        ShopCart shopCart = new ShopCart(id, cartId, userId);
        int result = shopCartService.addShopCart(shopCart);
        ResponseEntity.ok(resp,result);
    }

    // http://localhost:8080/shopCarts?m=delete&id=1432424303
    public void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        int result = shopCartService.deleteShopCart(id);
        ResponseEntity.ok(resp,result);
    }

    // http://localhost:8080/shopCarts?m=update&id=1432424303&user_id=1&cart_id=100000
    public void update(HttpServletRequest req, HttpServletResponse resp) throws IOException{

        String id = req.getParameter("id");
        String userId = req.getParameter("user_id");
        String cartId = req.getParameter("cart_id");
        ShopCart shopCart = new ShopCart(id, cartId, userId);
        int result = shopCartService.updateShopCart(shopCart);
        ResponseEntity.ok(resp,result);
    }

    // http://localhost:8080/shopCarts?m=page&current=1&pageSize=5
    public void page(HttpServletRequest req, HttpServletResponse resp) throws IOException{
        String current = req.getParameter("current");
        String pageSize = req.getParameter("pageSize");
        // 查询用户
        PageEntity<ShopCart> pageEntity = shopCartService.findShopCartPage(Integer.valueOf(current), Integer.valueOf(pageSize));
        // 转换为JSON,通过流发送给客户端
        ResponseEntity.ok(resp, pageEntity);
    }

}
